package com.zhouxin.customview.view

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import androidx.core.graphics.withSave
import com.zhouxin.customview.R
import com.zhouxin.customview.extensions.dp2px

private val IMAGE_WIDTH = 200f.dp2px
private val IMAGE_PADDING = 100f.dp2px

class CameraView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val clipped = Path().apply {
        addOval(
            IMAGE_PADDING,
            IMAGE_PADDING,
            IMAGE_PADDING + IMAGE_WIDTH,
            IMAGE_PADDING + IMAGE_WIDTH,
            Path.Direction.CW
        )
    }
    private val camera = Camera()

    init {
        camera.rotateX(-30f)
        //动态适配手机机型，“-6”这个值根据实际情况自己定
        camera.setLocation(0f, 0f, -6 * resources.displayMetrics.density)
    }

    override fun onDraw(canvas: Canvas) {
        /*//切一个圆形区域
        canvas.clipPath(clipped)*/

        //上半部分
        //下面倒着看好理解，实际运行时正着运行的
        canvas.save()//save()和restore()常常配合clipXXX使用
        //6.移回
        canvas.translate(IMAGE_PADDING + IMAGE_WIDTH / 2f, IMAGE_PADDING + IMAGE_WIDTH / 2f)
        //5，旋转
        canvas.rotate(-30f)
        //4.翻转
        camera.applyToCanvas(canvas)
        //3.裁切
        canvas.clipRect(-IMAGE_WIDTH, -IMAGE_WIDTH, IMAGE_WIDTH, 0f)
        //2.旋转
        canvas.rotate(30f)
        //1.移动
        canvas.translate(-(IMAGE_PADDING + IMAGE_WIDTH / 2f), -(IMAGE_PADDING + IMAGE_WIDTH / 2f))
        canvas.drawBitmap(getAvatar(IMAGE_WIDTH.toInt()), IMAGE_PADDING, IMAGE_PADDING, paint)
        canvas.restore()

        /*下半部分*/
        canvas.save()
        canvas.translate(IMAGE_PADDING + IMAGE_WIDTH / 2f, IMAGE_PADDING + IMAGE_WIDTH / 2f)
        canvas.rotate(-30f)
        canvas.clipRect(-IMAGE_WIDTH, 0f, IMAGE_WIDTH, IMAGE_WIDTH)
        canvas.rotate(30f)
        canvas.translate(-(IMAGE_PADDING + IMAGE_WIDTH / 2f), -(IMAGE_PADDING + IMAGE_WIDTH / 2f))
        canvas.drawBitmap(getAvatar(IMAGE_WIDTH.toInt()), IMAGE_PADDING, IMAGE_PADDING, paint)
        canvas.restore()

    }

    private fun getAvatar(width: Int): Bitmap {
        val options = BitmapFactory.Options()
        //只测量图片尺寸
        options.inJustDecodeBounds = true
        BitmapFactory.decodeResource(resources, R.drawable.fire_bg, options)
        options.inJustDecodeBounds = false
        //原图多大
        options.inDensity = options.outWidth
        //目标多大
        options.inTargetDensity = width
        //得到的bitmap就会根据options.inDensity和options.inTargetDensity的比例缩放至需要的大小，优化了图片的加载
        return BitmapFactory.decodeResource(resources, R.drawable.fire_bg, options)
    }
}